<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置弹层 -->
      <el-dialog
        title="新增角色"
        :visible.sync="showDialog"
        width="40%"
        @close="btnCancel"
      >
        <el-form ref="ruleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" style="50%" size="mini" />

          </el-form-item>

          <el-form-item label="启用" prop="state">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>

          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="submitForm('ruleForm')">确定</el-button>
                <el-button size="mini" @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>

        </el-form></el-dialog>

      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editObj.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else>{{ row.state===1?"已启用":"未启用" }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editObj.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row.id)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :current-page.sync="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据(必须设置node-key) -->
      <el-tree
        ref="tree"
        check-strictly
        node-key="id"
        :default-checked-keys="permIds"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
      />
      <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
      <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
    </el-dialog>
  </div>

</template>
<script>
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { transListToTreeData } from '@/utils/index'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {

      currentRoleId: null, // 当前id
      permIds: [], // 角色所拥有的权限数据

      showPermissionDialog: false, // 控制弹层显示隐藏
      permissionData: [],

      showDialog: false,
      pageParams: {
        page: 1, // 第几页
        pagesize: 10, // 每页多少条
        total: 0
      },
      list: [],
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnPermissionOK() {
      await assignPerm({ id: this.currentRoleId, permIds:
      this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      // console.log(rows)
      this.list = rows
      this.pageParams.total = total

      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editObj', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状态
      // 更新缓存数据
      row.editObj.name = row.name
      row.editObj.state = row.state
      row.editObj.description = row.description
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.getRoleList()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        } else {
          this.$refs.formName.resetFields() // 重置表单数据
          this.showDialog = false // 关闭弹层
        }
      })
    },
    btnCancel() {
      console.log('关闭按钮按下')
      this.$refs.ruleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    async  btnEditOK(row) {
      if (row.editObj.name && row.editObj.description) {
      // 下一步操作
        await updateRole({ ...row.editObj, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target, source)
        // 将 表单 里的新数据row.editObj,更新到表格row
        Object.assign(row, {
          ...row.editObj,
          isEdit: false // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.error('角色和描述不能为空')
      }
    },
    async confirmDel(id) {
      console.log(id, 'id')
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
